/**
 * TicTacToeView
 * 
 * @constructor
 * @param {JQuery} jqTable The JQuery table reference
 * 
 */
function TicTacToeView(jqTable) {
	this.jqTable = jqTable;
}

TicTacToeView.prototype.init = function(game) {
	this.game = game;
	this.initCellClickHandlers();
};

TicTacToeView.prototype.initCellClickHandlers = function() {
	var game = this.game;

	this.iterateTableCells(function(tableCell, row, col) {
		tableCell.on('click', function() {
			game.move(row, col);
		});
	});
};

TicTacToeView.prototype.update = function(gameBoard) {
	function getCellClass(player) {
		var result = 'player';

		if (Player.X === player) {
			result += 'X';
		} else if (Player.O === player) {
			result += 'O';
		} else if (Player.NONE === player) {
			result += 'None';
		}

		return result;
	}

	this.iterateTableCells(function(tableCell, row, col) {
		var player = gameBoard.get(row, col);
		var cellClass = getCellClass(player);

		tableCell.removeClass().addClass(cellClass);
		tableCell.text(player.toString());
	});
};

TicTacToeView.prototype.iterateTableCells = function(handler) {
	var width = this.game.getBoard().getWidth();
	var height = this.game.getBoard().getHeight();

	for (var row = 0; row < height; row++) {
		for (var col = 0; col < width; col++) {
			handler(this.getCell(row, col), row, col);
		}
	}
};

TicTacToeView.prototype.getCell = function(row, col) {
	var uiTable = this.jqTable;
	var tableRow = uiTable.find('tr:nth-child(' + (row + 1) + ')');
	var tableCell = tableRow.find('td:nth-child(' + (col + 1) + ')');

	return tableCell;
};

TicTacToeView.prototype.onWin = function(winningPlayer, winningCells) {
	for (var i = 0; i < winningCells.length; i++) {
		var cell = winningCells[i];
		var tableCell = this.getCell(cell.row, cell.col);
		tableCell.addClass('win');
	}

	alert(winningPlayer + " has won!");

	this.iterateTableCells(function(tableCell, row, col) {
		tableCell.off('click');
	});
};